# 这是一个示例 Python 脚本。

# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。

import serial
import time
import datetime

# 全局变量
current_datetime = datetime.datetime.now()
cur_time = current_datetime.strftime('%H:%M:%S')

def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


class SpcSerial:
    name = "serialX"
    port = "/dev/ttyAMA0"
    baudrate = 115200
    serial = serial.Serial()

    def __init__(self, name = "serialX",
                 port = "COM3",
                 baudrate = 115200):
        self.name = name
        self.port = port
        self.baudrate = baudrate
        print(name," ",port, " baud=",baudrate)
        self.serial = serial.Serial(port, baudrate, timeout=0.01)
        return

    def __del__(self):
        print(self.name," is delet\n")
        self.serial.__del__()
        return

    def Open(self):
        if self.serial.isOpen():
            pass
        else:
            self.serial.open()

        print(self.name," is open\n")
        return

    def Close(self):
        if self.serial.isOpen():
            self.serial.close()
        else:
            pass
        print(self.name, " is close\n")
        return

    def Send(self,data = b"__?__"):
        # self.serial.write(data.encode("utf-8"))
        self.serial.write(data)
        return

    def ReadLine(self):
        # data = self.serial.readline()
        data = self.serial.read(1024)
        dataArray = list(data)
        datalen = len(dataArray)
        return (data, datalen)


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print_hi('com_data_transport')
    pending = 0
    hex_show_max_col = 16   # 每行显示hex数量


    while True:
        try:
            uart_1 = SpcSerial(name = "dev", port="COM4", baudrate=115200)
            pending = 1
            uart_2 = SpcSerial(name="pc", port="COM5", baudrate=115200)
            pending = 2

            uart_1.Open()
            uart_2.Open()

            while (True):
                (data_dev, data_len) = uart_1.ReadLine()
                if (data_len > 0):
                    cur_time = datetime.datetime.now().strftime('%H:%M:%S')
                    uart_2.Send(data_dev)

                    print(f"[{cur_time}]{uart_1.name}-->{uart_2.name} recv {data_len} Btye >>")
                    # print("[hex]>> ", end='')
                    data_show = ''
                    col = 0
                    for data in data_dev:
                        data_show += '{:02x} '.format(data)
                        col += 1
                        if col >= hex_show_max_col:
                            print(f"{data_show}")
                            data_show = ''
                            col = 0

                (data_dev, data_len) = uart_2.ReadLine()
                if (data_len > 0):
                    cur_time = datetime.datetime.now().strftime('%H:%M:%S')
                    uart_1.Send(data_dev)
                    print(f"[{cur_time}]{uart_2.name}-->{uart_1.name} recv {data_len} Btye >>")
                    # print("[hex]>> ", end='')
                    data_show = ''
                    col = 0
                    for data in data_dev:
                        data_show += '{:02x} '.format(data)
                        col += 1
                        if col >= hex_show_max_col:
                            print(f"{data_show}")
                            data_show = ''
                            col = 0

                time.sleep(0.01)
        except serial.SerialException as err:
            print(f"{datetime.datetime.now().strftime('%H:%M:%S')} exception: {err.args[0]}")
            if pending >= 1:
                uart_1.__del__()
            if pending >= 2:
                uart_2.__del__()
                
            pending = 0
            time.sleep(5)





# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
